const deAttr = () => ({
    data: null,//*
    images: [],//*
    onEnd: null,//*

    beginTime: 0,//开始时间
    jumpTime: 1000,//变化时间
    intervalTime: 500,//间隔时间
    lastTime: 0,//当前图片开始的时间
    isRepeat: 1,//是否重复播放

    imageIndex: 0,//图片开始下标
    state: 0,//0为关闭,1为启动
});

export default class ImageJume {
    constructor(attr) {
        Object.assign(this, deAttr(), attr);
        this.init();
    }

    init() {
        this.state = 0;
    }

    start(ms) {
        this.state = 1;
        this.beginTime = Date.now() + ms;
        this.lastTime = this.beginTime;
        this.loadImage();
        if (this.isRepeat) {
            this.images.push(this.images[0]);
        }
    }

    update() {
        const { jumpTime, intervalTime, lastTime, state } = this;

        const curTime = Date.now();
        if (curTime > this.beginTime && state) {

            var ret = (curTime - lastTime) / jumpTime * 1.0;
            this.data.set = ret;

            if (ret >= 1.0) {
                //此时已经更新完成
                //加载下一张图片
                this.loadImage();
                this.beginTime = curTime + intervalTime;
                this.lastTime = curTime + intervalTime;
            }

        }
    }

    loadImage() {
        const { images, isRepeat, onEnd } = this;
        if (this.imageIndex + 1 >= images.length) {
            if (isRepeat)
                this.imageIndex = 0;
            else {
                this.over();
                return;
            }
        }

        this.data.set = 0;
        onEnd([images[this.imageIndex], images[this.imageIndex + 1]]);
        this.imageIndex++;
    }

    over() {
        this.state = 0;
    }
}